import {computed, ref} from 'vue'
import {defineStore} from 'pinia'
import {loginApi, logoutApi, registerApi, userGetApi} from "@/api/path/account";
import {ElMessage} from "element-plus";
import { obsClient } from '@/utils/obs';
import {useSocketStore} from "@/stores/socket";

const notLoggedInUser = {
    id: -1,
    name: '未登录',
    email: '未登录',
    avatar: ''
};
const nullEnterprise = {
    enterpriseId: null,
    enterpriseName: null,
    is_admin: false
};

export const useAccountStore = defineStore('account', () => {
    const user = ref(notLoggedInUser);
    const enterprise = ref(nullEnterprise);
    let avatar_id = -1;

    const socketStore = useSocketStore();
    const hasLogin = computed(() => {
        return user.value.id !== -1;
    });
    const hasEnterprise = computed(() => {
        return enterprise.value.enterpriseId !== null;
    });
    const login = async (account: string, password: string) => {
        const response = await loginApi(account, password);
        if (response.errno === 1) {
            user.value = response.user;
            enterprise.value = response.enterprise;

            await socketStore.connect(); // 连接socket

            ElMessage.success('登录成功');
        }
        else {
            if (response.errno === 1003) {
                await userGet();
            }
            ElMessage.warning(response.msg);
        }
        return response;
    };
    const logout = async () => {
        const response = await logoutApi();
        user.value = notLoggedInUser;
        enterprise.value = nullEnterprise;
        if (response.errno === 1) {
            socketStore.disconnect(); // 断开socket

            ElMessage.success('退出成功');
        }
        else {
            ElMessage.warning(response.msg);
        }
        return response;
    };

    const register = async (user_name: string, email: string, password: string, password_repeat: string) => {
        const response = await registerApi(user_name, email, password, password_repeat);
        if (response.errno === 1) {
            ElMessage.success('注册成功');
        }
        else {
            ElMessage.warning(response.msg);
        }
        return response;
    };

    const userGet = async () => {
        const response = await userGetApi();
        if (response.errno === 1) {
            user.value = response.user;
            enterprise.value = response.enterprise;
            requestAvatar(user.value.id)

            await socketStore.connect(); // 连接socket
        }
        return response;
    };
    // 获取头像
    const requestAvatar = (id) => {
        const obs = obsClient; 
        obs.listObjects({
            Bucket: 'job-linker',
            Prefix: "personal/avatar/" + id + '/',
        }).then(result => {
            if (result.CommonMsg.Status < 300 && result.InterfaceResult.Contents && result.InterfaceResult.Contents.length > 0) {
                let contents = result.InterfaceResult.Contents
                let element = contents[0]
                let index = 0
                for (index = contents.length - 1; index >= 0; index--) {
                    element = contents[index]
                    if (element.Key.endsWith('.jpeg') && element.Key.startsWith('personal/avatar/' + id + '/')) {
                    break
                    }
                }
                if (index<0) {
                    return
                }
                avatar_id = index + 1
                let path = element.Key
                return obsClient.getObject({
                    Bucket: 'job-linker',
                    Key: path,
                    SaveByType: 'arraybuffer',
                }).then(result => {
                    if (result.CommonMsg.Status < 300) {
                    const arrayBuffer = result.InterfaceResult.Content;
                    const blob = new Blob([arrayBuffer], { type: 'image/jpeg' });
                    const url = URL.createObjectURL(blob);
                    user.value.avatar = url; 
                    }
                });
            }
        }).catch(error => {
            console.error('请求头像列表时发生错误：', error);
            ElMessage({
            message: '请求头像列表失败。',
            type: 'error',
        });
        });
    };

    return {
        user,
        enterprise,
        hasLogin,
        hasEnterprise,
        login,
        logout,
        register,
        userGet
    };

}, {
    persist: {
        enabled: true,
    }
})